package com.svs.web.controller.system;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;


import com.svs.common.base.AjaxResult;
import com.svs.framework.web.BackendController;
import com.svs.system.service.UploadService;

@Controller
public class UploadController extends BackendController {

	@Autowired
	UploadService uploadService ;
	
	
	@ResponseBody
	@RequestMapping(value = "/uploadImage/{category}")
    public AjaxResult uploadFile(@PathVariable("category")String category ,HttpServletRequest request) throws Exception {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> files = multipartRequest.getFileMap();
        for (String key : files.keySet()) {
            MultipartFile item = files.get(key);
            // 判断文件名
            String image = uploadService.handleFileUploadNoDomain(item,category);
            return success(image) ;
        }
        return error() ;
    }
	 //多图片上传
    @ResponseBody
    @RequestMapping(value = "/moreUploadImage/{category}")
    public AjaxResult moreUploadFile(@PathVariable("category")String category ,HttpServletRequest request) throws Exception {

        List<String> fileList = new ArrayList<>();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultiValueMap<String, MultipartFile> files = multipartRequest.getMultiFileMap();
        Set<String> keys = files.keySet();//遍历文件


        for (String key:keys) {
            List<MultipartFile> mutiFiles = files.get(key);
            for (MultipartFile file : mutiFiles) {
                // 判断文件名
                String message = uploadService.handleFileUploadNoDomain(file,category);
                fileList.add(message);
            }
        }

        JSONArray json = new JSONArray();
        for(String val : fileList){
            /* List jo = new ArrayList();*/
            json.add(val);
            /* json.add(jo);*/
        }

        if(json.size() > 0){
            return success(json.toJSONString()) ;
        }
        return error() ;
    }

}
